<!--接害人员台账   injuredPersonnel-->
<template>
  <Layout>
    <Form ref="form1" :model="dataToQuery" :label-width="120">
      <Row v-show="!switchFlag" class="query-form" >
        <Col span="8">
          <FormItem label="企业名称：" prop="order">
            <cascader-dom class="query-form-el" ref='queryOrgCascader' @setOrgInfo='setQueryCompanyName'
                          :orgTree="true"
                          :setCurrentName="{label:dataToQuery.companyName,value:dataToQuery.companyId}"></cascader-dom>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="人员名称：" prop="content" >
            <Input class='query-form-el' type='text' v-model='dataToQuery.name'></Input>
          </FormItem>
        </Col>
        <Col span="8">
          <Button @click="switchQuery(true)" class="ivu-btn-switch" type="text"  >展开∨</Button>
          <Button @click="reset" class="ivu-btn-reset"  >重置</Button>
          <Button type="primary" class="ivu-btn-query"   icon="md-search"  @click="query">查询</Button>
        </Col>
      </Row>
      <Row v-show="switchFlag" class="query-form">
        <Col span="8">
          <FormItem label="企业名称：" prop="order">
            <cascader-dom class="query-form-el" ref='queryOrgCascader1' @setOrgInfo='setQueryCompanyName' :orgTree="true" :setCurrentName="{label:dataToQuery.companyName,value:dataToQuery.companyId}"></cascader-dom>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="人员名称：" prop="content" >
            <Input class='query-form-el' type='text' v-model='dataToQuery.name'></Input>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label='危害因素：' prop='hazardsFactorArr'>
            <Select class='query-form-el' placeholder="请选择危害因素" type='text' v-model='dataToQuery.hazardsFactorArr' multiple>
              <OptionGroup :label="type.name" v-for="type in hazardsTypeMap">
                <Option v-for="factor in type.children" :value="factor.id" :key="factor.id">{{ factor.name }}</Option>
              </OptionGroup>
            </Select>
          </FormItem>
        </Col>
      </Row>
      <Row v-show="switchFlag" class="query-form">
        <Col span="8">
          <FormItem label='接害岗位：' prop='injuredPostId'>
            <Select class='query-form-el' placeholder="请选择接害岗位" type='text' v-model='dataToQuery.injuredPostId'>
              <Option v-for="(item,key) in injuredPostMap" :value="key" :key="key">{{ item.name }}</Option>
            </Select>
          </FormItem>
        </Col>
        <Col span="8" offset="8">
          <Button @click="switchQuery(false)" class="ivu-btn-switch" type="text">收起∧</Button>
          <Button @click="reset" class="ivu-btn-reset">重置</Button>
          <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
        </Col>
      </Row>
      <Row class="query-form">
        <Col span="24">
          <Button size="large" :loading='pageStatus.baseDataloading' class="ivu-btn-add" icon="md-add"  @click="addInfo">新增</Button>
        </Col>
      </Row>
    </Form>
    <Table ref='table' :height="tableHeight"  no-data-text="没有查询到相关数据!" @on-selection-change = 'getSelectRows' :loading='pageStatus.loading || pageStatus.baseDataloading'
           border :columns="columns1"  :data="dataTable" >
    </Table>
    <Row style="margin-right:10px;">
      <Col span="24" >
        <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize" @on-change="pageChange"
              @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray" show-total show-sizer
              show-elevator/>
        <!--<Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize" @on-change="pageChange" @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray" show-total show-sizer show-elevator />-->
      </Col>
    </Row>
    <Modal  title="接害人员台账" :transfer=false :mask-closable="false" v-model="dialogShow" v-if="dataToView && dialogShow"  :width=800 :styles="{height:'514px'}"  class-name='limit-height-dialog'>
      <Row>
        <Col span="24">
          <Form ref="dialogForm" :class="mode === 'view'?'modal-view-detail':''" :show-message="false" :model="dataToView" :rules="mode === 'view'?{}:ruleCustom" :label-width="mode === 'view'?100:null" :label-position="mode === 'view'?'right':'top'">
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label='企业名称：' prop='eventOrgId'>
                  <div v-if="mode === 'view'">{{dataToView.companyName}}</div>
                  <cascader-dom v-else ref='orgCascader'
                                @setOrgInfo='(data)=>{cascaderDomIdChangeHandle(data,"companyId");}'
                                @setOrgname='(data)=>{cascaderDomNameChangeHandle(data,"companyName");}'
                                :orgTree="true" :currentOrgId="dataToView.companyId"
                                :setCurrentName="{label:dataToView.companyName,value:dataToView.companyId}">
                  </cascader-dom>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label='姓名：' prop='name'>
                  <div v-if="mode === 'view'">{{ dataToView.name }}</div>
                  <Input v-else class=''placeholder="请填写姓名" type='text' v-model='dataToView.name'></Input>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label='性别：' prop='gender'>
                  <div v-if="mode === 'view'">{{ dataToView.gender==1?'男':'女' }}</div>
                  <Select v-else class=''placeholder="请选择性别" type='text' v-model='dataToView.gender'>
                    <Option  value="1" >男</Option>
                    <Option  value="2" >女</Option>
                  </Select>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label='出生日期：' prop='birthDate'>
                  <div v-if="mode === 'view'">{{ dataToView.birthDate.substr(0,10) }}</div>
                  <DatePicker v-else class="w" placeholder="请选择出生日期" v-model='dataToView.birthDate' ></DatePicker>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label='身份证号：' prop='idCard'>
                  <div v-if="mode === 'view'">{{ dataToView.idCard }}</div>
                  <Input v-else class=''placeholder="请填写身份证号" maxlength="18" type='text' v-model='dataToView.idCard'></Input>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label='是否在岗：' prop='onDuty'>
                  <div v-if="mode === 'view'">{{ dataToView.onDuty==1?'是':'否' }}</div>
                  <Select v-else class=''placeholder="请选择是否在岗" type='text' v-model='dataToView.onDuty'>
                    <Option  value="1" >是</Option>
                    <Option  value="0" >否</Option>
                  </Select>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label='岗位工龄：' prop='workYears'>
                  <div v-if="mode === 'view'">{{ dataToView.workYears }}</div>
                  <InputNumber v-else class='w'placeholder="请填写岗位工龄" :min="0" type='text' v-model='dataToView.workYears'></InputNumber>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label='接害岗位：' prop='injuredPostId'>
                  <div v-if="mode === 'view'">{{ injuredPostMap[dataToView.injuredPostId].name }}</div>
                  <Select v-else class=''placeholder="请选择接害岗位" type='text' v-model='dataToView.injuredPostId'>
                    <Option v-for="(item,key) in injuredPostMap" :value="key" :key="key">{{ item.name }}</Option>
                  </Select>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label='危害因素：' prop='hazardsFactorArr'>
                  <div v-if="mode === 'view'">{{ dataToView.hazardsFactorStr }}</div>
                  <Select v-else class=''placeholder="请选择危害因素" type='text' v-model='dataToView.hazardsFactorArr' multiple placement="top">
                    <OptionGroup :label="type.name" v-for="type in hazardsTypeMap">
                      <Option v-for="factor in type.children" :value="factor.id" :key="factor.id">{{ factor.name }}</Option>
                    </OptionGroup>
                  </Select>
                </FormItem>
              </Col>
            </Row>
          </Form>
        </Col>
      </Row>
      <div slot="footer">
        <Button v-if="mode != 'view'" type="primary"  class='ivu-btn-save' @click="submit('dialogForm')" >确定</Button>
        <Button v-if="mode != 'view'" type="primary"  class='ivu-btn-cancel' @click="handleCancel" >取消</Button>
        <Button v-if="mode === 'view'" class='ivu-btn-save' @click="dialogShow=false">关闭</Button>
      </div>
    </Modal>
  </Layout>
</template>

<script>
    import {Api} from '@/api/index.js'
    import {formatDate} from '@/tools/index'
    import _uniq from 'lodash/uniq'
    var cascaderDom = () => import('@/components/cascader-dom.vue');
    import pageCommonFunction from '@/components/pageCommonFunction.js'

    export default {
        components:{
            cascaderDom
        },
        data(){
            return{
                ...this.createCommonDataField(),
                columns1: [
                    { title: '序号', width: 80, fixed: 'left', align: 'center', render: this.indexColumnsRender},
                    { key:'name',title: '姓名',  align: 'center', minWidth:120 },
                    { key:'companyName',title: '企业名称',  align: 'center', minWidth:240 },
                    { key:'gender',title: '性别',  align: 'center', render:(h, params)=>{return h('span', params.row.gender==1?'男':'女')}, minWidth:120},
                    { key:'birthDate',title: '出生日期',  align: 'center' , render: this.renderCellDate, minWidth:120},
                    { key:'idCard',title: '身份证号',  align: 'center', minWidth:160 },
                    { key:'onDuty',title: '是否在岗',  align: 'center', render:(h, params)=>{return h('span', params.row.onDuty==1?'是':'否')}, minWidth:120 },
                    { key:'workYears',title: '岗位工龄',  align: 'center', minWidth:120},
                    { key:'injuredPostId',title: '接害岗位',  align: 'center' ,render:(h, params)=>{return h('span', this.injuredPostMap[params.row.injuredPostId].name)}, minWidth:120},
                    { key:'hazardsType',title: '危害因素类型',  align: 'center' ,render:(h, params)=>{
                            var arr = params.row.hazardsType.split(','), resArr = []
                            for (var i = 0, il = arr.length; i < il; i++) {
                                var id = arr[i]
                                if (id in this.hazardsTypeMap) {
                                    resArr.push(this.hazardsTypeMap[id].name)
                                }
                                return h('span', resArr.join('、'))
                            }
                        }, minWidth: 120
                    },
                    { key: 'hazardsFactorArr', title: '危害因素', align: 'center', render: (h, params) => {
                            var arr = params.row.hazardsFactor.split(','), resArr = []
                            for (var i = 0, il = arr.length; i < il; i++) {
                                var id = arr[i]
                                if (id in this.hazardsFactorMap) {
                                    resArr.push(this.hazardsFactorMap[id].name)
                                }
                            }
                            return h('span', resArr.join('、'))
                        }, minWidth:180},
                    this.getActionColumns(),
                ],
                ruleCustom : {
                    name: [ { required: true, message: '请填写姓名', trigger: 'change',}],
                    companyId: [ { required: true, message: '请填写企业ID', trigger: 'change',}],
                    companyName: [ { required: true, message: '请填写企业名称', trigger: 'change',}],
                    gender: [ { required: true, message: '请填写性别', trigger: 'change',}],
                    birthDate: [ { required: true, message: '请填写出生日期', trigger: 'change',type:'date'}],
                    idCard: [
                        { required: true, message: '请填写身份证号', trigger: 'change'},
                        { validator: this.idCardValidator,  trigger: 'change' }
                    ],
                    onDuty: [ { required: true, message: '请填写是否在岗', trigger: 'change',}],
                    injuredPostId: [ { required: true, message: '请填写接害岗位', trigger: 'change',}],
                    workYears: [ { required: true, message: '请填写岗位工龄', trigger: 'change',type: 'number'}],
                    hazardsType: [ { required: true, message: '请填写危害因素类型', trigger: 'change',}],
                    hazardsFactor: [ { required: true, message: '请填写危害因素', trigger: 'change', type:'array'}],
                },
                tableHeight:10,
                hazardsTypeMap:{},
                hazardsFactorMap:{},
                injuredPostMap:{},
                // api
                queryUrl:Api.queryHealthApi.replace('{{type}}','injuredPersonnel'),
                exportUrl:Api.exportHealthApi.replace('{{type}}','injuredPersonnel'),
                deleteUrl:Api.deleteHealthApi.replace('{{type}}','injuredPersonnel'),
                bthDeleteUrl:Api.batchDeleteHealthApi.replace('{{type}}','injuredPersonnel'),
                getUrl:Api.getHealthApi.replace('{{type}}','injuredPersonnel'),
                updateUrl:Api.updateHealthApi.replace('{{type}}','injuredPersonnel'),
                saveUrl:Api.saveHealthApi.replace('{{type}}','injuredPersonnel'),
                // type api
                getAllHazardsTypeUrl:Api.getAllHealthApi.replace('{{type}}','hazardsType'),
                getAllHazardsFactorUrl:Api.getAllHealthApi.replace('{{type}}','hazardsFactor'),
                getAllInjuredPostUrl:Api.getAllHealthApi.replace('{{type}}','injuredPost'),
            }
        },
        async mounted() {
            this.setTableHeight();
            this.pageStatus.baseDataloading = true
            await Promise.all([
                this.$http.get(this.getAllHazardsTypeUrl, {}),
                this.$http.get(this.getAllHazardsFactorUrl, {}),
                this.$http.get(this.getAllInjuredPostUrl, {})
            ]).then((results) => {
                // 危害因素类型
                let hazardsTypeMap = {}
                let list = results[0].body.data
                for (let i = 0, il = list.length; i < il; i++) {
                    let typeObj = list[i]
                    typeObj.children = []
                    hazardsTypeMap[typeObj.id] = typeObj
                }

                // 危害因素
                let hazardsFactorMap = {}
                list = results[1].body.data
                for (let i = 0, il = list.length; i < il; i++) {
                    let obj = list[i]
                    hazardsFactorMap[obj.id] = obj
                    if (obj.typeId in hazardsTypeMap) {
                        hazardsTypeMap[obj.typeId].children.push(obj)
                    }
                }
                console.log(hazardsTypeMap)

                // 接害岗位
                let injuredPostMap = {}
                list = results[2].body.data
                for (let i = 0, il = list.length; i < il; i++) {
                    let obj = list[i]
                    injuredPostMap[obj.id] = obj
                }

                this.hazardsTypeMap = hazardsTypeMap
                this.hazardsFactorMap = hazardsFactorMap
                this.injuredPostMap = injuredPostMap
            }).catch((error) => {
                console.log(error)
            })
            this.pageStatus.baseDataloading = false
            this.query();
        },

        methods:{
            ...pageCommonFunction,
            beforeViewDialogOpen(data){
                var arr = data.row.hazardsFactor.split(','), resArr = []
                for (var i=0,il=arr.length;i<il;i++) {
                    resArr.push(this.hazardsFactorMap[arr[i]].name)
                }
                data.row.hazardsFactorStr = resArr.join('、')
            },
            beforeEditDialogOpen(data){
                data.row.hazardsFactorArr = data.row.hazardsFactor.split(',')
            },
            deleteData(params) {
                this.deleteDateAjax(params);
            },
            query() {
                if(this.dataToQuery.hazardsFactorArr) {
                    var hazardsFactorArr = this.dataToQuery.hazardsFactorArr,
                        hazardsTypeArr = []
                    for (var i=0,il=hazardsFactorArr.length;i<il;i++){
                        hazardsTypeArr.push(this.hazardsFactorMap[hazardsFactorArr[i]].typeId)
                    }
                    hazardsTypeArr = _uniq(hazardsTypeArr)
                    this.dataToQuery.hazardsFactor = this.arrayToInFormat(hazardsFactorArr)
                }
                this.queryAjax();
            },
            submit(name) {
                var hazardsFactorArr = this.dataToView.hazardsFactorArr,
                    hazardsTypeArr = []
                for (var i=0,il=hazardsFactorArr.length;i<il;i++){
                    hazardsTypeArr.push(this.hazardsFactorMap[hazardsFactorArr[i]].typeId)
                }
                hazardsTypeArr = _uniq(hazardsTypeArr)
                this.dataToView.hazardsFactor = hazardsFactorArr.join(',')
                this.dataToView.hazardsType = hazardsTypeArr.join(',')
                this.submitAjax(name);
            },
            createEmptyDataToAdd(){
                return {
                    workYears:'',
                    hazardsFactorArr: [],
                }
            }
        },
        watch: {},
    }
</script>

<style lang='css' scoped>
  .rpt-form {
  }
  .rpt-form{}
  /deep/ .rpt-form .query-form-el{width:100%;}
  /deep/ .rpt-form .ivu-form-item{margin-bottom: 24px;}

</style>
